<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="资产名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入资产名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
            <el-option
              v-for="dict in typeOptions"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="资产状态" prop="assetStatus">
          <el-select v-model="queryParams.assetStatus" placeholder="请选择资产状态" clearable>
            <el-option
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上架状态" prop="auditStatus">
          <el-select v-model="queryParams.auditStatus" placeholder="请选择上架状态" clearable>
            <el-option
              v-for="dict in auditStatusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="contactUnit">
          <el-input
            v-model="queryParams.contactUnit"
            placeholder="请输入联系人"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="出让价格" prop="transferPrice">
          <el-input
            v-model="queryParams.transferPrice"
            placeholder="请输入出让价格"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input
            v-model="queryParams.address"
            placeholder="请输入详细地址"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    <div class="app_box">
    
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['assets:asset:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['assets:asset:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['assets:asset:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['assets:asset:export']"
          >导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['assets:asset:import']"
          >导入</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-dropdown @command="handleAudit" v-hasPermi="['assets:asset:audit']">
            <el-button :disabled="multiple" type="primary" plain>
              <el-icon><Tools /></el-icon>批量审核<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="1">批量上架</el-dropdown-item>
                <el-dropdown-item command="0">批量下架</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-col>
        <right-toolbar v-model="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="assetList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="资产图片" align="center" prop="imageUrl" width="120">
          <template #default="scope">
            <image-preview
              :src="scope.row.imageUrl" 
              width="80"
              height="60"
            />
          </template>
        </el-table-column>
        <el-table-column label="资产名称" align="center" prop="name" :show-overflow-tooltip="true" />
        <el-table-column label="类型" align="center" prop="type">
          <template #default="scope">
            <dict-tag :options="typeOptions" :value="scope.row.type"/>
          </template>
        </el-table-column>
        <el-table-column label="所属单位" align="center" prop="ownerUnit" :show-overflow-tooltip="true" />
        <el-table-column label="面积" align="center" prop="area" />
        <el-table-column label="楼栋/单元/房号" align="center" prop="buildingInfo" :show-overflow-tooltip="true">
          <template #header>
            <span>位置信息</span>
          </template>
          <template #default="scope">
            {{ getBuildingInfo(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column label="所在楼层" align="center" prop="floor" />
        <el-table-column label="层高" align="center" prop="floorHeight" />
        <el-table-column label="用途类型" align="center" prop="usageType" :show-overflow-tooltip="true" />
        <el-table-column label="盘活方式" align="center" prop="revitalizationMethod" :show-overflow-tooltip="true" />
        <el-table-column label="权利性质" align="center" prop="pricePropertyNature" :show-overflow-tooltip="true" />
        <el-table-column label="租赁期限" align="center" prop="leaseTerm" />
        <el-table-column label="出租价格" align="center" prop="rent" />
        <el-table-column label="出售价格" align="center" prop="transferPrice" />
        <el-table-column label="联系人" align="center" prop="contactUnit" :show-overflow-tooltip="true" />
        <el-table-column label="联系方式" align="center" prop="contactInformation" />
        <el-table-column label="详细地址" align="center" prop="address" :show-overflow-tooltip="true" />
        <el-table-column label="经度" align="center" prop="longitude" :show-overflow-tooltip="true" />
        <el-table-column label="纬度" align="center" prop="latitude" :show-overflow-tooltip="true" />
        <el-table-column label="评估时间" align="center" prop="evaluationTime" width="100">
          <template #default="scope">
            <span>{{ scope.row.evaluationTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="土地性质" align="center" prop="landNature" :show-overflow-tooltip="true" />
        <el-table-column label="装修" align="center" prop="decoration" />
        <el-table-column label="建筑年代" align="center" prop="buildingAge" />
        <el-table-column label="资产状态" align="center" prop="assetStatus">
          <template #default="scope">
            <dict-tag :options="statusOptions" :value="scope.row.assetStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="上架状态" align="center" prop="auditStatus">
          <template #default="scope">
            <dict-tag :options="auditStatusOptions" :value="scope.row.auditStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
          <template #default="scope">
            <el-button
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['assets:asset:edit']"
            >修改</el-button>
            <el-button
              type="danger"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['assets:asset:remove']"
            >删除</el-button>
            <el-button
              v-if="scope.row.auditStatus === 0"
              type="success"
              icon="Check"
              @click="handleAuditSingle(scope.row, 1)"
              v-hasPermi="['assets:asset:audit']"
            >上架</el-button>
            <el-button
              v-if="scope.row.auditStatus === 1"
              type="info"
              icon="Close"
              @click="handleAuditSingle(scope.row, 0)"
              v-hasPermi="['assets:asset:audit']"
            >下架</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </div>

    <!-- 添加或修改资产对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="资产名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入资产名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择类型">
                <el-option
                  v-for="dict in typeOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="面积" prop="area">
              <el-input v-model="form.area" placeholder="请输入面积" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="租赁期限" prop="leaseTerm">
              <el-input v-model="form.leaseTerm" placeholder="请输入租赁期限" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactUnit">
              <el-input v-model="form.contactUnit" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contactInformation">
              <el-input v-model="form.contactInformation" placeholder="请输入联系方式" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="form.longitude" placeholder="请输入经度（选填）" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input v-model="form.latitude" placeholder="请输入纬度（选填）" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属单位" prop="ownerUnit">
              <el-input v-model="form.ownerUnit" placeholder="请输入所属单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用途类型" prop="usageType">
              <el-input v-model="form.usageType" placeholder="请输入用途类型" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="盘活方式" prop="revitalizationMethod">
              <el-input v-model="form.revitalizationMethod" placeholder="请输入盘活方式" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权利性质" prop="pricePropertyNature">
              <el-input v-model="form.pricePropertyNature" placeholder="请输入价格权利性质" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="评估时间" prop="evaluationTime">
              <el-input
                v-model="form.evaluationTime"
                placeholder="请输入评估时间"
                clearable
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="土地性质" prop="landNature">
              <el-input v-model="form.landNature" placeholder="请输入土地性质" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="装修" prop="decoration">
              <el-input v-model="form.decoration" placeholder="请输入装修情况" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="建筑年代" prop="buildingAge">
              <el-input v-model="form.buildingAge" placeholder="请输入建筑年代" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="楼栋" prop="building">
              <el-input v-model="form.building" placeholder="楼栋" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单元" prop="unit">
              <el-input v-model="form.unit" placeholder="单元" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="房号" prop="roomNumber">
              <el-input v-model="form.roomNumber" placeholder="房号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所在楼层" prop="floor">
              <el-input v-model="form.floor" placeholder="请输入所在楼层" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="层高" prop="floorHeight">
              <el-input v-model="form.floorHeight" placeholder="请输入层高" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="出租价格" prop="rent">
              <el-input v-model="form.rent" placeholder="请输入出租价格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产状态" prop="assetStatus">
              <el-select v-model="form.assetStatus" placeholder="请选择资产状态">
                <el-option
                  v-for="dict in statusOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="排序" prop="sorted">
              <el-input-number v-model="form.sorted" placeholder="请输入排序值" :min="0" :max="9999" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上架状态" prop="auditStatus">
              <el-select v-model="form.auditStatus" placeholder="请选择上架状态">
                <el-option
                  v-for="dict in auditStatusOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="出售价格" prop="transferPrice">
              <el-input v-model="form.transferPrice" placeholder="请输入出售价格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="资产图片">
              <image-upload v-model="form.imageUrl" :limit="20"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="详情介绍" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 资产导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="downloadTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-checkbox v-model="upload.updateSupport" />更新已经存在的资产数据
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Picture, UploadFilled, Tools, ArrowDown } from '@element-plus/icons-vue';
import { listAsset, getAsset, addAsset, updateAsset, delAsset, batchDeleteAsset, batchAuditAsset, exportAsset, importTemplate, importAsset } from "@/api/assets/assets";
import { useDict } from '@/utils/dict';
import { getToken } from '@/utils/auth';
import noImage from '@/assets/images/no-image.png';
import ImagePreview from '@/components/ImagePreview/index.vue';

const { proxy } = getCurrentInstance();

// 组件变量
const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const showSearch = ref(true);
const total = ref(0);
const assetList = ref([]);
const title = ref("");
const open = ref(false);
const queryFormRef = ref();
const formRef = ref();
const uploadRef = ref();

// 字典
const { asset_type: typeOptions, asset_status: statusOptions, audit_status: auditStatusOptions } = proxy.useDict("asset_type", "asset_status", "audit_status");

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: null,
  type: null,
  assetStatus: null,
  auditStatus: null,
  contactUnit: null,
  transferPrice: null,
  address: null
});

// 表单参数
const form = reactive({
  id: null,
  name: null,
  type: null,
  area: null,
  leaseTerm: null,
  contactUnit: null,
  contactInformation: null,
  address: null,
  floor: null,
  buildingAge: null,
  assetStatus: 0,
  auditStatus: 0,
  rent: null,
  transferPrice: null,
  imageUrl: null,
  remark: null,
  longitude: null,
  latitude: null,
  ownerUnit: null,
  usageType: null,
  evaluationTime: null,
  landNature: null,
  decoration: null,
  building: null,
  unit: null,
  roomNumber: null,
  floorHeight: null,
  revitalizationMethod: null,
  pricePropertyNature: null
});

// 表单校验
const rules = {
  name: [
    { required: true, message: "资产名称不能为空", trigger: "blur" }
  ],
  type: [
    { required: true, message: "类型不能为空", trigger: "change" }
  ],
  area: [
    { required: true, message: "面积不能为空", trigger: "blur" }
  ],
  contactUnit: [
    { required: true, message: "联系人不能为空", trigger: "blur" }
  ],
  contactInformation: [
    { required: true, message: "联系方式不能为空", trigger: "blur" }
  ],
  address: [
    { required: true, message: "详细地址不能为空", trigger: "blur" }
  ],
  assetStatus: [
    { required: true, message: "资产状态不能为空", trigger: "change" }
  ]
};

// 上传参数
const upload = reactive({
  open: false,
  title: "",
  isUploading: false,
  updateSupport: false,
  headers: { Authorization: "Bearer " + getToken() },
  url: import.meta.env.VITE_APP_BASE_API + "/assets/asset/importData"
});

// 生命周期钩子
onMounted(() => {
  getList();
});

// 方法定义
/** 查询资产列表 */
const getList = () => {
  loading.value = true;
  listAsset(queryParams).then(response => {
    assetList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
};

// 取消按钮
const cancel = () => {
  open.value = false;
  resetForm();
};

// 表单重置
const resetForm = () => {
  form.id = null;
  form.name = null;
  form.type = null;
  form.area = null;
  form.leaseTerm = null;
  form.contactUnit = null;
  form.contactInformation = null;
  form.address = null;
  form.floor = null;
  form.buildingAge = null;
  form.assetStatus = 0;
  form.auditStatus = 0;
  form.rent = null;
  form.transferPrice = null;
  form.imageUrl = null;
  form.remark = null;
  form.longitude = null;
  form.latitude = null;
  form.ownerUnit = null;
  form.usageType = null;
  form.evaluationTime = null;
  form.landNature = null;
  form.decoration = null;
  form.building = null;
  form.unit = null;
  form.roomNumber = null;
  form.floorHeight = null;
  form.revitalizationMethod = null;
  form.pricePropertyNature = null;
  form.sorted = null;
  formRef.value && formRef.value.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value && queryFormRef.value.resetFields();
  handleQuery();
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  resetForm();
  open.value = true;
  title.value = "添加资产";
};

/** 修改按钮操作 */
const handleUpdate = (row) => {
  resetForm();
  const id = row.id || ids.value[0];
  getAsset(id).then(response => {
    Object.assign(form, response.data);
    open.value = true;
    title.value = "修改资产";
  });
};

/** 提交按钮 */
const submitForm = () => {
  formRef.value.validate(valid => {
    if (valid) {
      if (form.id) {
        updateAsset(form).then(response => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addAsset(form).then(response => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
};

/** 删除按钮操作 */
const handleDelete = (row) => {
  const deleteIds = row.id || ids.value;
  ElMessageBox.confirm('是否确认删除资产编号为"' + deleteIds + '"的数据项？').then(() => {
    return batchDeleteAsset(deleteIds);
  }).then(() => {
    getList();
    ElMessage.success("删除成功");
  }).catch(() => {});
};

/** 导出按钮操作 */
const handleExport = () => {
  ElMessageBox.confirm('是否确认导出所有资产数据项？').then(() => {
    proxy.download('assets/asset/export', {
      ...queryParams
    }, `asset_${new Date().getTime()}.xlsx`);
  }).catch(() => {});
};

/** 导入按钮操作 */
const handleImport = () => {
  upload.title = "资产导入";
  upload.open = true;
};

/** 下载模板操作 */
const downloadTemplate = () => {
  proxy.download("assets/asset/importTemplate", {
  }, `asset_template_${new Date().getTime()}.xlsx`);
};

// 文件上传中处理
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};

// 文件上传成功处理
const handleFileSuccess = (response) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value.clearFiles();
  ElMessageBox.alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};

// 提交上传文件
const submitFileForm = () => {
  uploadRef.value.submit();
};

/** 批量审核操作 */
const handleAudit = (auditStatus) => {
  if (ids.value.length === 0) {
    ElMessage.error("请至少选择一条记录");
    return;
  }
  // 确保auditStatus是数字类型
  const status = parseInt(auditStatus);
  const statusText = status === 1 ? "上架" : "下架";
  ElMessageBox.confirm('确认要' + statusText + '选中的资产吗？').then(() => {
    return batchAuditAsset(ids.value, status);
  }).then(() => {
    getList();
    ElMessage.success(statusText + "成功");
  }).catch(() => {});
};

/** 单个审核操作 */
const handleAuditSingle = (row, auditStatus) => {
  const id = row.id;
  const statusText = auditStatus === 1 ? "上架" : "下架";
  ElMessageBox.confirm('确认要' + statusText + '该资产吗？').then(() => {
    return batchAuditAsset([id], auditStatus);
  }).then(() => {
    getList();
    ElMessage.success(statusText + "成功");
  }).catch(() => {});
};

/** 获取第一张图片（缩略图） */
const getFirstImage = (imageUrl) => {
  if (!imageUrl) {
    return noImage;
  }
  const images = imageUrl.split(',');
  const firstImage = images[0];
  // 检查是否已经包含完整的URL路径
  if (firstImage.indexOf('http') === 0) {
    return firstImage;
  } else {
    return import.meta.env.VITE_APP_BASE_API + firstImage;
  }
};

/** 获取所有图片（预览用） */
const getPreviewImages = (imageUrl) => {
  if (!imageUrl) {
    return [noImage];
  }
  const images = imageUrl.split(',');
  return images.map(img => {
    if (img.indexOf('http') === 0) {
      return img;
    } else {
      return import.meta.env.VITE_APP_BASE_API + img;
    }
  });
};

/** 获取楼栋/单元/房号 */
const getBuildingInfo = (row) => {
  const parts = [];
  
  // 处理楼栋
  if (row.building && row.building.trim()) {
    parts.push(row.building.trim());
  }
  
  // 处理单元
  if (row.unit && row.unit.trim()) {
    parts.push(row.unit.trim());
  }
  
  // 处理房号
  if (row.roomNumber && row.roomNumber.trim()) {
    parts.push(row.roomNumber.trim());
  }
  
  return parts.length > 0 ? parts.join('/') : '-';
};

/** 获取楼栋/单元/房号标签 */
const getBuildingInfoLabel = (row) => {
  const hasBuilding = row.building && row.building.trim();
  const hasUnit = row.unit && row.unit.trim();
  const hasRoomNumber = row.roomNumber && row.roomNumber.trim();
  
  if (hasBuilding && hasUnit && hasRoomNumber) {
    return "楼栋/单元/房号";
  } else if (hasBuilding && hasUnit) {
    return "楼栋/单元";
  } else if (hasBuilding && hasRoomNumber) {
    return "楼栋/房号";
  } else if (hasUnit && hasRoomNumber) {
    return "单元/房号";
  } else if (hasBuilding) {
    return "楼栋";
  } else if (hasUnit) {
    return "单元";
  } else if (hasRoomNumber) {
    return "房号";
  } else {
    return "";
  }
};

/** 格式化时间 */
const parseTime = (time, format) => {
  if (!time) return '-';
  const date = new Date(time);
  if (isNaN(date.getTime())) return '-';
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  
  return `${year}-${month}-${day}`;
};
</script>